<template>
  <div class="house-visualization">
    <div class="visualization-header">
      <h2>
        <span v-if="!selectedRoom">房屋可视化</span>
        <span v-else>{{ selectedRoom }} - 详细视图</span>
      </h2>
      <div class="header-actions">
        <el-button v-if="selectedRoom" @click="selectedRoom = null" type="primary" size="small">
          <el-icon><ArrowLeft /></el-icon>
          返回总览
        </el-button>
        <div class="legend">
          <div class="legend-item">
            <div class="legend-icon device-on"></div>
            <span>设备开启</span>
          </div>
          <div class="legend-item">
            <div class="legend-icon device-off"></div>
            <span>设备关闭</span>
          </div>
        </div>
      </div>
    </div>

    <div class="house-container">
      <!-- 房屋总览视图 -->
      <svg v-if="!selectedRoom" class="house-svg" viewBox="0 0 800 600" xmlns="http://www.w3.org/2000/svg">
        <!-- 房屋外墙 -->
        <rect x="50" y="100" width="700" height="450" fill="#f8f9fa" stroke="#333" stroke-width="3"/>
        
        <!-- 房间循环渲染（概览模式） -->
        <g v-for="(roomConfig, roomName) in roomConfigs" :key="roomName" class="room-overview" :data-room="roomName">
          <!-- 房间背景 -->
          <rect 
            :x="roomConfig.x" 
            :y="roomConfig.y" 
            :width="roomConfig.width" 
            :height="roomConfig.height" 
            :fill="roomConfig.color" 
            :stroke="roomConfig.borderColor" 
            stroke-width="2"
            class="room-clickable"
            @click="selectRoom(roomName)"
          />
          
          <!-- 房间标签 -->
          <text 
            :x="roomConfig.x + roomConfig.width / 2" 
            :y="roomConfig.y + 25" 
            text-anchor="middle" 
            class="room-label clickable"
            @click="selectRoom(roomName)"
          >{{ roomName }}</text>
          
          <!-- 房间设备概览 -->
          <text 
            :x="roomConfig.x + roomConfig.width / 2" 
            :y="roomConfig.y + 45" 
            text-anchor="middle" 
            class="room-info"
            @click="selectRoom(roomName)"
          >{{ getRoomDevices(roomName).length }}台设备</text>
          
          <text 
            :x="roomConfig.x + roomConfig.width / 2" 
            :y="roomConfig.y + 65" 
            text-anchor="middle" 
            class="room-status"
            :fill="getActiveDevicesInRoom(roomName) > 0 ? '#ff9800' : '#757575'"
            @click="selectRoom(roomName)"
          >{{ getActiveDevicesInRoom(roomName) }}台运行中</text>
          
          <!-- 设备概览图标 -->
          <g v-for="(device, index) in getRoomDevices(roomName).slice(0, 4)" :key="device?.id || `device-${index}`">
            <circle 
              v-if="device && device.type"
              :cx="roomConfig.x + 30 + (index % 2) * 40" 
              :cy="roomConfig.y + roomConfig.height - 50 + Math.floor(index / 2) * 20"
              r="6" 
              :fill="device.status === 'on' ? getDeviceColor(device.type, true) : '#bdbdbd'"
              :stroke="device.status === 'on' ? getDeviceColor(device.type, false) : '#757575'"
              stroke-width="1"
              class="mini-device-icon"
              @click.stop="selectRoomAndDevice(roomName, device)"
            />
          </g>
          
          <!-- 更多设备提示 -->
          <text 
            v-if="getRoomDevices(roomName).length > 4"
            :x="roomConfig.x + roomConfig.width - 20" 
            :y="roomConfig.y + roomConfig.height - 20" 
            text-anchor="middle" 
            class="more-devices"
            @click="selectRoom(roomName)"
          >+{{ getRoomDevices(roomName).length - 4 }}</text>
          
          <!-- 点击提示 -->
          <text 
            :x="roomConfig.x + roomConfig.width / 2" 
            :y="roomConfig.y + roomConfig.height - 10" 
            text-anchor="middle" 
            class="click-hint"
            @click="selectRoom(roomName)"
          >点击查看详情</text>
        </g>

        <!-- 门 -->
        <rect x="370" y="545" width="60" height="10" fill="#8d6e63" stroke="#5d4037" stroke-width="1"/>
        <text x="400" y="570" text-anchor="middle" class="door-label">入口</text>
      </svg>
      
      <!-- 房间详细视图 -->
      <svg v-else class="house-svg" viewBox="0 0 800 600" xmlns="http://www.w3.org/2000/svg">
        <!-- 房间背景 -->
        <rect x="50" y="50" width="700" height="500" :fill="roomConfigs[selectedRoom]?.color || '#f8f9fa'" stroke="#333" stroke-width="3" rx="10"/>
        
        <!-- 房间标题 -->
        <text x="400" y="90" text-anchor="middle" class="room-title">{{ selectedRoom }}</text>
        
        <!-- 详细设备显示 -->
        <g v-for="device in getRoomDevices(selectedRoom)" :key="device?.id || 'unknown'" class="device-detail">
          <g v-if="device && device.type" :transform="`translate(${getDetailDevicePosition(device, selectedRoom).x}, ${getDetailDevicePosition(device, selectedRoom).y})`">
            <!-- 设备背景框 -->
            <rect 
              x="-50" y="-40" width="100" height="80" rx="8"
              fill="#fff" stroke="#ddd" stroke-width="1"
              class="device-background"
            />
            
            <!-- 灯光设备 -->
            <circle 
              v-if="device.type === 'light'"
              cx="0" cy="-10" r="20" 
              :fill="device.status === 'on' ? '#ff9800' : '#bdbdbd'"
              :stroke="device.status === 'on' ? '#f57c00' : '#757575'"
              stroke-width="3"
              class="device-icon clickable"
              @click="toggleDevice(device.id)"
            />
            
            <!-- 空调设备 -->
            <rect 
              v-else-if="device.type === 'air_conditioner'"
              x="-25" y="-25" width="50" height="30" rx="8"
              :fill="device.status === 'on' ? '#ff9800' : '#bdbdbd'"
              :stroke="device.status === 'on' ? '#f57c00' : '#757575'"
              stroke-width="3"
              class="device-icon clickable"
              @click="toggleDevice(device.id)"
            />
            
            <!-- 窗帘设备 -->
            <rect 
              v-else-if="device.type === 'curtain'"
              x="-20" y="-30" width="40" height="50"
              :fill="device.status === 'on' ? '#ff9800' : '#bdbdbd'"
              :stroke="device.status === 'on' ? '#f57c00' : '#757575'"
              stroke-width="3"
              class="device-icon clickable"
              @click="toggleDevice(device.id)"
            />
            
            <!-- 设备名称 -->
            <text 
              x="0" y="25" 
              text-anchor="middle" 
              class="device-name"
              @click="selectDevice(device)"
            >{{ device.name }}</text>
            
            <!-- 设备状态 -->
            <text 
              x="0" y="35" 
              text-anchor="middle" 
              class="device-status-text"
              :fill="device.status === 'on' ? '#ff9800' : '#f44336'"
            >{{ device.status === 'on' ? '开启' : '关闭' }}</text>
            
            <!-- 设备属性显示 -->
            <text 
              v-if="device.type === 'light' && device.status === 'on'"
              x="0" y="-35" 
              text-anchor="middle" 
              class="device-property"
            >{{ device.brightness }}%</text>
            
            <text 
              v-else-if="device.type === 'air_conditioner' && device.status === 'on'"
              x="0" y="-35" 
              text-anchor="middle" 
              class="device-property"
            >{{ device.temperature }}°C</text>
            
            <text 
              v-else-if="device.type === 'curtain' && device.status === 'on'"
              x="0" y="-35" 
              text-anchor="middle" 
              class="device-property"
            >{{ device.position }}%</text>
          </g>
        </g>
        
        <!-- 空状态 -->
        <g v-if="getRoomDevices(selectedRoom).length === 0">
          <text x="400" y="300" text-anchor="middle" class="empty-room">此房间暂无设备</text>
          <text x="400" y="320" text-anchor="middle" class="empty-hint">请到设备管理页面添加设备</text>
        </g>
      </svg>
    </div>

    <!-- 设备详情面板 -->
    <div class="device-details" v-if="selectedDevice">
      <div class="details-header">
        <h3>{{ selectedDevice.name }}</h3>
        <el-button size="small" @click="selectedDevice = null">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
      <div class="details-content">
        <p><strong>房间：</strong>{{ selectedDevice.room }}</p>
        <p><strong>类型：</strong>{{ getDeviceTypeName(selectedDevice.type) }}</p>
        <p><strong>状态：</strong>
          <el-tag :type="(selectedDevice.status === 'on' ? 'success' : 'info') || 'info'">
            {{ selectedDevice.status === 'on' ? '开启' : '关闭' }}
          </el-tag>
        </p>
        
        <!-- 设备特定属性 -->
        <div v-if="selectedDevice.type === 'light'" class="device-properties">
          <p><strong>亮度：</strong>{{ selectedDevice.brightness }}%</p>
          <p><strong>颜色：</strong>
            <span class="color-preview" :style="{ backgroundColor: selectedDevice.color }"></span>
            {{ selectedDevice.color }}
          </p>
        </div>
        
        <div v-else-if="selectedDevice.type === 'air_conditioner'" class="device-properties">
          <p><strong>温度：</strong>{{ selectedDevice.temperature }}°C</p>
          <p><strong>模式：</strong>{{ getModeText(selectedDevice.mode) }}</p>
          <p><strong>风速：</strong>{{ getFanSpeedText(selectedDevice.fanSpeed) }}</p>
        </div>
        
        <div v-else-if="selectedDevice.type === 'curtain'" class="device-properties">
          <p><strong>位置：</strong>{{ selectedDevice.position }}%</p>
        </div>
        
        <div class="device-actions">
          <el-button 
            :type="(selectedDevice.status === 'on' ? 'danger' : 'success') || 'primary'"
            @click="toggleDevice(selectedDevice.id)"
          >
            {{ selectedDevice.status === 'on' ? '关闭' : '开启' }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 房间统计信息 -->
    <div class="room-stats">
      <h3>房间统计</h3>
      <div class="stats-grid">
        <div v-for="(roomConfig, roomName) in roomConfigs" :key="roomName" class="room-stat">
          <div class="room-stat-header">
            <span class="room-name">{{ roomName }}</span>
            <span class="device-count">{{ getRoomDevices(roomName).length }}台设备</span>
          </div>
          <div class="room-stat-status">
            <span class="active-count">{{ getActiveDevicesInRoom(roomName) }}台运行中</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { Close, ArrowLeft } from '@element-plus/icons-vue'
import { useDeviceStore } from '../store/deviceStore.js'
import { ElMessage } from 'element-plus'

export default {
  name: 'HouseVisualization',
  components: {
    Close,
    ArrowLeft
  },
  setup() {
    const deviceStore = useDeviceStore()
    const selectedDevice = ref(null)
    const selectedRoom = ref(null)

    // 房间配置
    const roomConfigs = {
      '客厅': { x: 60, y: 110, width: 320, height: 200, color: '#e3f2fd', borderColor: '#1976d2' },
      '卧室': { x: 390, y: 110, width: 350, height: 200, color: '#f3e5f5', borderColor: '#7b1fa2' },
      '厨房': { x: 60, y: 320, width: 200, height: 220, color: '#e8f5e8', borderColor: '#2e7d32' },
      '卫生间': { x: 270, y: 320, width: 180, height: 220, color: '#fff3e0', borderColor: '#f57c00' },
      '书房': { x: 460, y: 320, width: 280, height: 220, color: '#fce4ec', borderColor: '#c2185b' }
    }

    // 获取指定房间的设备
    const getRoomDevices = (roomName) => {
      if (!deviceStore.devices.value || !Array.isArray(deviceStore.devices.value)) {
        return []
      }
      return deviceStore.devices.value.filter(device => 
        device && device.room === roomName && device.type
      )
    }

    // 获取房间中活跃设备数量
    const getActiveDevicesInRoom = (roomName) => {
      return getRoomDevices(roomName).filter(device => 
        device && device.status === 'on'
      ).length
    }

    // 获取设备在房间中的位置
    const getDevicePosition = (device, roomName) => {
      if (!device || !device.id) return { x: 100, y: 100 }
      
      const room = roomConfigs[roomName]
      if (!room) return { x: 100, y: 100 }

      const roomDevices = getRoomDevices(roomName)
      const deviceIndex = roomDevices.findIndex(d => d && d.id === device.id)
      const totalDevices = roomDevices.length

      if (deviceIndex === -1) return { x: 100, y: 100 }

      if (totalDevices === 1) {
        return { 
          x: room.x + room.width / 2, 
          y: room.y + room.height / 2 + 10 
        }
      }

      // 根据设备数量和索引计算位置
      const cols = Math.ceil(Math.sqrt(totalDevices))
      const rows = Math.ceil(totalDevices / cols)
      
      const col = deviceIndex % cols
      const row = Math.floor(deviceIndex / cols)
      
      const spacingX = (room.width - 60) / (cols + 1)
      const spacingY = (room.height - 80) / (rows + 1)
      
      return {
        x: room.x + 30 + spacingX * (col + 1),
        y: room.y + 50 + spacingY * (row + 1)
      }
    }

    // 获取设备标签偏移量
    const getDeviceLabelOffset = (deviceType) => {
      switch (deviceType) {
        case 'light': return 25
        case 'air_conditioner': return 25
        case 'curtain': return 35
        default: return 25
      }
    }

    // 获取详细视图中设备的位置
    const getDetailDevicePosition = (device, roomName) => {
      if (!device || !device.id) return { x: 150, y: 150 }
      
      const roomDevices = getRoomDevices(roomName)
      const deviceIndex = roomDevices.findIndex(d => d && d.id === device.id)
      
      if (deviceIndex === -1) return { x: 150, y: 150 }
      
      const totalDevices = roomDevices.length

      // 计算网格布局
      const cols = Math.min(4, Math.ceil(Math.sqrt(totalDevices)))
      
      const col = deviceIndex % cols
      const row = Math.floor(deviceIndex / cols)
      
      const startX = 150
      const startY = 150
      const spacingX = 140
      const spacingY = 120
      
      return {
        x: startX + col * spacingX,
        y: startY + row * spacingY
      }
    }

    // 获取设备颜色 - 统一开启状态颜色
    const getDeviceColor = (deviceType, isFill) => {
      // 所有设备开启时使用统一的橙色系
      const colors = {
        'light': isFill ? '#ff9800' : '#f57c00',      // 橙色系
        'air_conditioner': isFill ? '#ff9800' : '#f57c00',  // 橙色系
        'curtain': isFill ? '#ff9800' : '#f57c00'     // 橙色系
      }
      return colors[deviceType] || (isFill ? '#bdbdbd' : '#757575')
    }

    // 选择房间
    const selectRoom = (roomName) => {
      selectedRoom.value = roomName
      selectedDevice.value = null // 清除设备选择
    }

    // 选择房间和设备
    const selectRoomAndDevice = (roomName, device) => {
      selectedRoom.value = roomName
      selectedDevice.value = device
    }

    // 选择设备
    const selectDevice = (device) => {
      selectedDevice.value = device
    }

    // 切换设备状态
    const toggleDevice = async (deviceId) => {
      try {
        await deviceStore.toggleDevice(deviceId)
        // 如果当前选中的设备被切换了，更新选中设备的状态
        if (selectedDevice.value && selectedDevice.value.id === deviceId) {
          selectedDevice.value = deviceStore.devices.value.find(d => d.id === deviceId)
        }
      } catch (error) {
        ElMessage.error('设备控制失败：' + error.message)
      }
    }

    // 获取设备类型名称
    const getDeviceTypeName = (type) => {
      const typeNames = {
        'light': '灯光',
        'air_conditioner': '空调',
        'curtain': '窗帘'
      }
      return typeNames[type] || type
    }

    // 获取空调模式文本
    const getModeText = (mode) => {
      const modes = {
        'cool': '制冷',
        'heat': '制热',
        'fan': '送风',
        'auto': '自动'
      }
      return modes[mode] || mode
    }

    // 获取风速文本
    const getFanSpeedText = (speed) => {
      const speeds = {
        'low': '低速',
        'medium': '中速',
        'high': '高速',
        'auto': '自动'
      }
      return speeds[speed] || speed
    }

    return {
      devices: deviceStore.devices,
      selectedDevice,
      selectedRoom,
      roomConfigs,
      getRoomDevices,
      getActiveDevicesInRoom,
      getDevicePosition,
      getDetailDevicePosition,
      getDeviceLabelOffset,
      getDeviceColor,
      selectRoom,
      selectRoomAndDevice,
      selectDevice,
      toggleDevice,
      getDeviceTypeName,
      getModeText,
      getFanSpeedText
    }
  }
}
</script>

<style scoped>
.house-visualization {
  padding: 20px;
  position: relative;
}

.visualization-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.visualization-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.legend {
  display: flex;
  gap: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
}

.legend-icon {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid;
}

.legend-icon.device-on {
  background-color: #ffd54f;
  border-color: #ff8f00;
}

.legend-icon.device-off {
  background-color: #bdbdbd;
  border-color: #757575;
}

.house-container {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.house-svg {
  width: 100%;
  height: auto;
  max-height: 600px;
}

.room-label {
  font-size: 16px;
  font-weight: 600;
  fill: #333;
}

.door-label {
  font-size: 12px;
  fill: #666;
}

.device-icon {
  cursor: pointer;
  transition: all 0.2s ease;
}

.device-icon:hover {
  transform: scale(1.1);
  filter: brightness(1.1);
}

.device-label {
  font-size: 10px;
  fill: #333;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.device-label:hover {
  fill: #1976d2;
  font-weight: 600;
}

.status-indicator {
  pointer-events: none;
}

.clickable {
  cursor: pointer;
}

/* 房间概览样式 */
.room-clickable {
  cursor: pointer;
  transition: all 0.3s ease;
}

.room-clickable:hover {
  filter: brightness(1.05);
  stroke-width: 3;
}

.room-info {
  font-size: 12px;
  fill: #666;
  cursor: pointer;
}

.room-status {
  font-size: 11px;
  font-weight: 500;
  cursor: pointer;
}

.mini-device-icon {
  cursor: pointer;
  transition: all 0.2s ease;
}

.mini-device-icon:hover {
  transform: scale(1.2);
}

.more-devices {
  font-size: 10px;
  fill: #999;
  font-weight: bold;
  cursor: pointer;
}

.click-hint {
  font-size: 10px;
  fill: #999;
  cursor: pointer;
  transition: fill 0.2s ease;
}

.click-hint:hover {
  fill: #1976d2;
}

/* 房间详细视图样式 */
.room-title {
  font-size: 24px;
  font-weight: 600;
  fill: #333;
}

.device-detail .device-background {
  transition: all 0.2s ease;
}

.device-detail:hover .device-background {
  stroke: #1976d2;
  stroke-width: 2;
  transform: scale(1.02);
}

.device-name {
  font-size: 12px;
  font-weight: 500;
  fill: #333;
  cursor: pointer;
}

.device-name:hover {
  fill: #1976d2;
}

.device-status-text {
  font-size: 10px;
  font-weight: 500;
}

.device-property {
  font-size: 10px;
  fill: #666;
  font-weight: 500;
}

.empty-room {
  font-size: 18px;
  fill: #999;
}

.empty-hint {
  font-size: 14px;
  fill: #bbb;
}

.device-details {
  position: fixed;
  top: 50%;
  right: 20px;
  transform: translateY(-50%);
  width: 300px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  z-index: 1000;
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0;
}

.details-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.details-content {
  padding: 20px;
}

.details-content p {
  margin: 10px 0;
  color: #666;
  font-size: 14px;
}

.device-properties {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.color-preview {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid #ddd;
  margin-right: 8px;
  vertical-align: middle;
}

.device-actions {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.room-stats {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.room-stats h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 18px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.room-stat {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  border-left: 4px solid #1976d2;
}

.room-stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.room-name {
  font-weight: 600;
  color: #333;
}

.device-count {
  font-size: 12px;
  color: #666;
  background: #e3f2fd;
  padding: 2px 8px;
  border-radius: 12px;
}

.room-stat-status {
  font-size: 14px;
  color: #666;
}

.active-count {
  color: #4caf50;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .device-details {
    position: relative;
    right: auto;
    top: auto;
    transform: none;
    width: 100%;
    margin-top: 20px;
  }
}

@media (max-width: 768px) {
  .house-visualization {
    padding: 10px;
  }
  
  .visualization-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .legend {
    justify-content: center;
  }
  
  .house-container {
    padding: 10px;
  }
  
  .room-label {
    font-size: 14px;
  }
  
  .device-label {
    font-size: 8px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>